#include "ModelImporter.h"
#include "Settings.h"
#include "Model.h"
#include <fstream>
#include <iostream>

using namespace std;
ModelImporter::ModelImporter(void)
{
}

ModelImporter::~ModelImporter(void)
{
}

/// Imports a mesh from a file, the caller must handle the free() of both buffers.
Model<Vector4>* ModelImporter::Import(string filename)
{
	int numVerts;
	int numFaces;
	Model<Vector4> *model = new Model<Vector4>();
    ifstream file = ifstream(filename.c_str());

    if (file.fail())
    {
        cout << "Problem openning file. Check that is in the Content folder." << endl;
		system("PAUSE");
        return NULL;
    }

	// Leemos el header del archivo.
    file >> numVerts;
    file >> numFaces;

	// Reservamos memoria para los buffers.
    Vector4 *positions = new Vector4[numVerts];
    int *indices = new int[numFaces * 3];

    // Cargamos los vertices del mesh.
    Settings::particleCount = numVerts;
    for (int i = 0; i < numVerts; i++)
    {
        file >> 
		positions[i].x >>
        positions[i].y >>
        positions[i].z >>
        positions[i].w;		// k.
    }
    cout << endl;

    // Cargamos los indices.
    Settings::faceCount = numFaces;
    for (int i = 0; i < numFaces * 3; i++)
    {
        file >> indices[i];
        indices[i]--;		// Los indices en el archivo no son zero based.
    }

    // Guardamos los datos en el modelo.
	model->SetVertexBuffer(numVerts, positions);
	model->SetIndexBuffer(numFaces * 3, indices);

	return model;
}
